<template>
  <el-upload
    class="upload_file"
    action=""
    list-type="text"
    accept=".xls,.xlsx"
    :limit="1"
    :auto-upload="false"
    :on-exceed="handleExceed"
    :before-upload="beforeUpdata"
    :on-change="handleChange"
    :file-list="uploadFileList"
    :on-remove="Remove">
    <template #default>
      <el-button >导入文件</el-button>
    </template>
  </el-upload>
</template>
<script setup lang="ts">
  import { ref, reactive, computed } from 'vue'
  import { ElForm, ElMessage } from 'element-plus'
  import type { UploadFile } from 'element-plus/es/components/upload/src/upload'
  import { getSetionId, getSuffixIcon } from '@/utils/utils'
  import {importTemplate} from '@/api/employe/employeetasks/taskmanage'
  const emit = defineEmits(['submit'])
  const props = defineProps(['object_type'])
  const formRef = ref<InstanceType<typeof ElForm>>()
  const dialogImageUrl = ref('')
  const dialogVisible = ref(false)
  const uploadFileList = ref([]);
  const task_type = ref(1);
  const beforeUpdata = async (file: any) => {
    const is2M = file.size / 1024 / 1024 <= 20
    const type = ['.xls','.xlsx'].includes(file.name.substr(file.name.lastIndexOf('.')))
    if(!type){
      ElMessage.warning(`上传的文件类型只支持.xls,.xlsx格式`)
    }
    if (!is2M) {
      ElMessage.warning(`上传的文件最大支持20M`)
    }
    return is2M&&type
  }
  const hideUpload = computed(()=>{
    return uploadFileList.value.length >= 1
  })
  const Remove = (file: UploadFile, list: UploadFile[]) => {
    console.log(file, list, '--自动删除')
    emit('submit', list)
  }
  // 上传改变
  const handleChange = async (file: UploadFile, list: UploadFile[]) => {
    let existFile = list.slice(0, list.length - 1).find((f) => f.name === file.name)
    if (existFile) {
      ElMessage.error('当前文件已经存在!')
      list.pop()
      return
    }
    let flag = await beforeUpdata(file);
    if(!flag){
      list.pop()
      return 
    }
    let form  = new FormData();
    form.append('file',file.raw)
    form.append('type',props.object_type) // 1线索 2客户
    try {
      const res:any = await importTemplate(form);
      uploadFileList.value.push({name:file.name})
      emit('submit',res);
    } catch (error) {
      // throw new Error(error);
      list.pop()
    }
  }
  const handleExceed = (files: UploadFile, list: UploadFile[]) => {
    ElMessage.warning(`当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + list.length} 个文件`)
  }
  defineExpose({
    task_type,
    uploadFileList
  })
</script>
<style lang="scss" scoped>
.upload_file{
  display:inline-block;
}
</style>